<?php

function setCurl( $option )
{
    $header     = [
        'Accept'        => 'application/json',
        'Content-Type'  => 'application/x-www-form-urlencoded',
        'Cache-Control' => 'no-cache',
    ];
    if( !empty( $option['header'] ) )
        $header = array_merge( $header, $option['header'] );

    $newHeader  = [];
    array_walk( $header, function( $v, $k ) use ( &$newHeader ) {
        $newHeader[]    = "{$k}: {$v}";
    } );

    $postfield  = '';
    if( $header['Content-Type'] == 'application/json' )
        $postfield          = empty( $option['post']) ? '' : json_encode( $option['post'] );
    else
        $postfield          = empty( $option['post']) ? '' : http_build_query( $option['post'] );
    unset( $header );

    $param      = [
        CURLOPT_URL             => $option['url'],
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_TIMEOUT         => 30,
        CURLOPT_HTTP_VERSION    => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST   => empty( $option['method'] ) ? 'GET' : strtoupper( $option['method'] ),
        CURLOPT_POSTFIELDS      => $postfield,
        CURLOPT_HTTPHEADER      => $newHeader,
    ];
//var_dump( $param );die;
    $ch         = curl_init();
    curl_setopt_array( $ch, $param );
    $response   = curl_exec( $ch );
    $err        = curl_error( $ch );
    $httpcode   = curl_getinfo( $ch, CURLINFO_HTTP_CODE );

    if( !in_array( $httpcode, [200, 201, 202, 204] ) || $err ) {
        var_dump( 'err' );
        var_dump( $httpcode );
        var_dump( $err );
        var_dump( $response );
        die;
    }


    return $response;
}


function getAccToken()
{
    $toke   = '{"scope":"https://api.paypal.com/v1/payments/.* https://uri.paypal.com/services/payments/refund https://uri.paypal.com/services/applications/webhooks https://uri.paypal.com/services/payments/payment/authcapture https://uri.paypal.com/payments/payouts https://api.paypal.com/v1/vault/credit-card/.* https://uri.paypal.com/services/disputes/read-seller https://uri.paypal.com/services/subscriptions https://uri.paypal.com/services/disputes/read-buyer https://api.paypal.com/v1/vault/credit-card openid https://uri.paypal.com/services/disputes/update-seller https://uri.paypal.com/services/payments/realtimepayment","nonce":"2018-07-24T02:25:11ZP0LHw5b2UIv89Zi7ikflSd0VnCC9jmrvy8vxGCplkZM","access_token":"A21AAGm3zPPgPg9lCwk29mSQdT2wy7qmiifGSFv2M3mHhFTF92DbA-HCHhoKZzVN0ST02XNp3aVWRpV7oYyLpvBUvaxUGK54g","token_type":"Bearer","app_id":"APP-80W284485P519543T","expires_in":32398}';
    return json_decode( $toke, true );

    $author     = base64_encode( 'AWRrvexWxlrL178urEumRqYos3uAIhmH0wVIFCJTL3-qvnL_VWoaiDcgBAe3MNltIFcQTqkh5Vju2-Us:EHpMgOlneBSaYk4G0KIV-Vbe9v-0ZoJ6hZ27YL0dQuXS5MG8L-8CqJkGMuVdkFY8IDXuvcNdudX-Aw-b' );
    $option     = [
        'url'       => 'https://api.sandbox.paypal.com/v1/oauth2/token',
        'method'    => 'post',
        'post'      => ['grant_type'=>'client_credentials'],
        'header'    => ['Authorization' => 'Basic '.$author]
    ];
    $res        = setCurl( $option );
    var_dump( $res );
}


function createPayment()
{

    $res    = '{"id":"PAY-02R10871UE014270BLNK2OEA","intent":"sale","state":"created","payer":{"payment_method":"paypal"},"transactions":[{"amount":{"total":"100.00","currency":"USD","details":{"subtotal":"100.00","tax":"0.00","shipping":"0.00","insurance":"0.00","handling_fee":"0.00","shipping_discount":"0.00"}},"description":"交易详情","item_list":{"items":[{"name":"商品1","sku":"123","description":"商品详情","price":"100.00","currency":"USD","tax":"0.00","quantity":1}]},"related_resources":[]}],"note_to_payer":"note message","create_time":"2018-07-23T09:59:43Z","links":[{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-02R10871UE014270BLNK2OEA","rel":"self","method":"GET"},{"href":"https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-8W879457GU9060341","rel":"approval_url","method":"REDIRECT"},{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-02R10871UE014270BLNK2OEA/execute","rel":"execute","method":"POST"}]}';
    print_r( json_decode( $res, true ) );
    return;
    $post       = [
        'intent'    => 'sale',
        'payer'     => [
            'payment_method'    => 'paypal'
        ],
        'transactions'  => [
            [
                'amount'    => [
                    'total' => 100.00,
                    'currency'  => 'USD',
                    'details'   => [
                        'subtotal'  => '100.00',
                        'tax'       => 0,
                        'shipping'  => 0,
                        'handling_fee'  => 0,
                        'insurance' => 0,
                        'shipping_discount'     => 0
                    ]
                ],
                'description'   => '交易详情',
                'item_list'     => [
                    'items'     => [
                        [
                            'name'  => '商品1',
                            'description'   => '商品详情',
                            'quantity'      => 1,
                            'price'         => 100,
                            'tax'           => 0,
                            'sku'           => '123',
                            'currency'      => 'USD'
                        ]
                    ]
                ],
            ]
        ],
        'note_to_payer' => 'note message',
        'redirect_urls' => [
            'return_url'    => 'https://ppt.vipwifi.com/paytest/payment_return_url.php',
            'cancel_url'    => 'https://ppt.vipwifi.com/paytest/payment_return_url.php',
        ],
    ];

    $acctoken   = getAccToken();
    $option     = [
        'url'       => 'https://api.sandbox.paypal.com/v1/payments/payment',
        'method'    => 'post',
        'post'      => $post,
        'header'    => [
            'Authorization'     => $acctoken['token_type'] . ' ' . $acctoken['access_token'],
            'Content-Type'      => 'application/json',
        ]
    ];
    $res        = setCurl( $option );
    var_dump( $res );
}

function getPayment()
{
    $acctoken   = getAccToken();
    $option     = [
        'url'       => 'https://api.sandbox.paypal.com/v1/payments/payment/PAY-02R10871UE014270BLNK2OEA',
        'method'    => 'get',
        'header'    => [
            'Authorization'     => $acctoken['token_type'] . ' ' . $acctoken['access_token'],
            'Content-Type'      => 'application/json',
        ]
    ];
    $res        = setCurl( $option );
    var_dump( $res );
}

var_dump( getAccToken() );
//    createPayment();
//      getPayment();
